package com.mybatis.boost.mapper.autoconfigure;

import com.mybatis.boost.mapper.SingleMapper;
import com.mybatis.boost.mapper.model.DatabaseDialects;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import tk.mybatis.mapper.entity.Config;

import javax.validation.constraints.NotNull;

import static com.mybatis.boost.mapper.autoconfigure.MapperProperties.UniqueIdType.UUID;
import static com.mybatis.boost.mapper.model.DatabaseDialects.MYSQL;

/**
 * @author jearton
 * @since 2017/2/6
 */
@Data
@ConfigurationProperties(prefix = "mybatis.mapper")
public class MapperProperties {

    /**
     * 指定通用Mapper接口
     */
    @NotEmpty
    private Class<?>[] mappers = {SingleMapper.class};

    /**
     * 唯一ID生成规则
     */
    @NotNull
    private UniqueIdType uniqueIdType = UUID;

    /**
     * 主键自增回写SQL
     */
    @NotNull
    private DatabaseDialects identity = MYSQL;

    /**
     * SelectKey的Order
     */
    private boolean before;

    Config toMapperConfig() {
        Config config = new Config();
        config.setUUID(uniqueIdType.getOgnl());
        config.setIDENTITY(identity.getIdentityRetrievalStatement());
        config.setBEFORE(before);
        return config;
    }

    public Class<?>[] getMappers() {
        return this.mappers;
    }

    @AllArgsConstructor
    @Getter
    enum UniqueIdType {

        ID_GENERATOR("全局唯一ID，Snowflake算法"),

        UUID("全局唯一ID");

        private String desc;

        private String getOgnl() {
            switch (this) {
                case ID_GENERATOR:
                    return "@com.mybatis.extend.id.IdHelper@getId()";
                default:
                    return "@java.util.UUID@randomUUID().toString().replace(\"-\", \"\")";
            }
        }
    }
}
